<?php

namespace App\Models;

use App\Traits\User\HasMenus;
use App\Traits\User\HasRoles;
use App\Traits\User\HasPermissions;
use Illuminate\Support\Facades\Cache;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * 用户数据模型
 *
 * @property $id
 * @property $admin
 * @property $roles
 * @property $permissions
 * @property $menus
 * @package App\Models
 * @author George <george@betterde.com>
 */
class User extends Authenticatable implements JWTSubject
{
    use Notifiable, SoftDeletes, HasRoles, HasPermissions, HasMenus;

    /**
     * 禁用rememberToken
     *
     * @var string
     */
    protected $rememberTokenName = '';

    /**
     * 定义可填充字段
     *
     * @var array
     */
    protected $fillable = [
        'name', 'staffid', 'gender', 'email', 'password', 'avatar', 'admin', 'role', 'remarks', 'phone'
    ];

    /**
     * 定义隐藏属性
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'deleted_at'
    ];

    /**
     * 定义用于获取用户信息的主键
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 自定义Payload内容
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 定义密码修改器
     *
     * Date: 2018/1/25
     * @author George
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    /**
     * 自定义隐式路由绑定实现缓存
     *
     * Date: 2018/1/25
     * @author George
     * @param mixed $value
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function resolveRouteBinding($value)
    {
        return Cache::remember("users:{$value}", 60, function () use ($value) {
            return $this->where($this->getRouteKeyName(), $value)->first();
        });
    }

    /**
     * 获取用户的门店
     *
     * Data: 2018/2/1
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function shops(){
        return $this->belongsToMany(Shop::class, 'shop_user_pivot', 'user_id', 'shop_id');
    }

    /**
     * 获取用户的任务提交数据
     *
     * @author Eric
     */
    public function xunDianJiLus()
    {
        return $this->hasMany(XunDianJiLu::class,'uid','id');
    }
}
